﻿Imports System.IO
Imports System.Net.Http
Imports System.Windows
Imports System.Windows.Controls
Imports System.Windows.Media.Imaging
Imports CommunityToolkit.Mvvm.ComponentModel
Imports CommunityToolkit.Mvvm.Input
Imports OpenSilver.Controls
Imports OpenSilver.IO

Public Class ProfileEditPageViewModel : Inherits ObservableObject
    Private _userEdited As User
    Public Property UserEdited As User
        Get
            Return _userEdited
        End Get
        Set(value As User)
            SetProperty(_userEdited, value)
        End Set
    End Property

    Private _errorMessage As String
    Public Property ErrorMessage As String
        Get
            Return _errorMessage
        End Get
        Set(value As String)
            SetProperty(_errorMessage, value)
        End Set
    End Property

    Private _userAvatar As BitmapImage
    Public Property UserAvatar As BitmapImage
        Get
            Return _userAvatar
        End Get
        Set(value As BitmapImage)
            SetProperty(_userAvatar, value)
        End Set
    End Property

    Private ReadOnly _client As HttpClientBase
    Private ReadOnly _fileClient As FileUploadHttpClient

    Public Property SaveProfileCommand As New AsyncRelayCommand(AddressOf SaveProfileClicked)
    Public Property CancelCommand As New RelayCommand(AddressOf CancelClicked)
    Public Property UploadAvatarCommand As New AsyncRelayCommand(AddressOf UploadAvatarClicked)

    Public Sub New()
        'UserEdited = UserSim
        _client = New HttpClientBase()
        _fileClient = New FileUploadHttpClient()
        Call InitProfile()
    End Sub

    Private Async Function InitProfile() As Task
        Try
            Dim response = Await _client.GetAsync(Of User)("vdm/api/account/findUser/id/" + Application.Current.Resources("UserId").ToString())
            If response.Code <> 200 Then
                MessageBox.Show("登录状态异常导致获取用户信息失败，请重新登录")
                NavigationService.Navigate(NavigationData.LOGIN_PAGE_URI)
                Return
            End If
            UserEdited = response.Data
            If Not String.IsNullOrEmpty(UserEdited.Avatar) Then
                UserAvatar = New BitmapImage(New Uri(UserEdited.Avatar, UriKind.Absolute))
            Else
                UserAvatar = New BitmapImage(New Uri("/VMDWebFrontend;component/Assets/SPGLP_icon.jpg", UriKind.Relative))
            End If
        Catch ex As Exception
            Console.WriteLine(ex.StackTrace)
            MessageBox.Show($"系统错误：{ex.Message}")
            NavigationService.Navigate(NavigationData.LOGIN_PAGE_URI)
        End Try
    End Function

    Private Async Function UploadAvatarClicked() As Task
        '打开文件对话框
        Try
            Dim openFileDialog As New OpenSilver.Controls.OpenFileDialog With {
                .Filter = "图片文件 (*.jpg, *.jpeg, *.png)|*.jpg;*.jpeg;*.png"
            }
            If Await openFileDialog.ShowDialogAsync = True Then
                '获取选择的文件路径
                Dim selectedFile As MemoryFileInfo = openFileDialog.File
                Dim originalFileName As String = selectedFile.Name
                Dim fileExtension As String = Path.GetExtension(originalFileName)
                Dim userId As String = Application.Current.Resources("UserId").ToString()
                Dim fileName As String = $"{userId}{fileExtension}"
                ' 使用MemoryFileInfo的OpenRead方法读取文件内容
                Using fileStream As Stream = selectedFile.OpenRead()
                    Using memoryStream As New MemoryStream()
                        Await fileStream.CopyToAsync(memoryStream)
                        Dim fileBytes As Byte() = memoryStream.ToArray()
                        ' 读取文件内容并添加到内容中
                        Dim fileContent As New ByteArrayContent(fileBytes)
                        Dim content As New MultipartFormDataContent()
                        fileContent.Headers.ContentDisposition = New System.Net.Http.Headers.ContentDispositionHeaderValue("form-data") With {
                            .Name = "file",
                            .FileName = fileName
                        }
                        content.Add(fileContent)
                        ' 调用服务端接口上传文件
                        Dim response = Await _fileClient.UploadFileAsync(content)
                        '获取服务器返回的头像地址
                        Dim serverImgUrl As String = response.Data
                        UserEdited.Avatar = Application.Current.Resources("UserId").ToString() & fileExtension
                        UserAvatar = New BitmapImage(New Uri(serverImgUrl, UriKind.Absolute))
                    End Using
                End Using
            End If
        Catch ex As Exception
            Console.WriteLine(ex.Message)
            Console.WriteLine(ex.StackTrace)
            MessageBox.Show($"系统错误：{ex.Message}")
            NavigationService.Navigate(NavigationData.LOGIN_PAGE_URI)
        End Try

    End Function

    Private Async Function SaveProfileClicked() As Task
        'Dim avatarUriString As String = UserAvatar.ToString()
        If String.IsNullOrWhiteSpace(UserEdited.Avatar) Then
            ErrorMessage = "头像上传失败，请重试"
            Return
        End If
        If String.IsNullOrEmpty(UserEdited.Username) OrElse UserEdited.Username.Length < 3 OrElse UserEdited.Username.Length > 10 OrElse UserEdited.Username.Contains(" ") Then
            ErrorMessage = "用户名不能为空，长度必须在 4 到 9 个字符之间，且不能包含空格"
            Return
        End If
        If String.IsNullOrEmpty(UserEdited.Phone) OrElse UserEdited.Phone.Length <> 11 OrElse Not UserEdited.Phone.All(Function(c) Char.IsDigit(c)) Then
            ErrorMessage = "手机号码不能为空，长度必须为 11 位数字"
            Return
        End If
        '修改用户信息
        '调用服务端接口修改用户信息
        Try
            'UserEdited.Avatar = avatarUriString
            Dim response = Await _client.PostAsync(Of User)(UserEdited, "vdm/api/account/editUser")
            If response.Code = 200 Then
                MessageBox.Show("用户信息修改成功")
            ElseIf response.Code = 400 Then
                MessageBox.Show("登录状态异常导致信息修改失败，请重新登录")
                NavigationService.Navigate(NavigationData.LOGIN_PAGE_URI)
            Else
                ErrorMessage = $"修改失败：{response.Message}"
            End If
        Catch ex As Exception
            ErrorMessage = $"系统错误：{ex.Message}"
            Return
        End Try
    End Function

    Private Sub CancelClicked()
        NavigationService.Navigate(NavigationData.MAIN_LAYOUT_URI)
    End Sub

End Class
